package jupiter.servlets;


import javax.jms.*;

import jupiter.channel.Global;
import jupiter.filters.Filter;
import jupiter.filters.FilterException;
import jupiter.message.Message;
import jupiter.util.Application;
import jupiter.util.Timey;


import org.apache.activemq.command.*;
import org.apache.activemq.util.ByteSequence;
import org.json.*;
import org.mortbay.jetty.RetryRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class MessageEventListener  implements MessageListener {

	Logger logger = LoggerFactory.getLogger(MessageEventListener.class);
	public void onMessage(javax.jms.Message msg) {
		  try {
			  String m = "";
			  if(msg==null)
			    logger.info("Message: message null");
			  else {
			    if(msg instanceof ObjectMessage) {
			        m = (String) ((ObjectMessage)msg).getObject();
			    } else if(msg instanceof TextMessage) {
			        m = ((TextMessage)msg).getText();
			    } else {
			        ActiveMQBytesMessage bytes_message = (ActiveMQBytesMessage)msg;
			        ByteSequence sequence = bytes_message.getContent();

			        for(int i=0; i < sequence.getData().length; i++) {
			            m += (char)sequence.getData()[i];
			        }
			    }
			  }
			  System.out.println(m);
			  Message message = new Message(m);
			  //System.out.println("Received -> "+message.toString());
			  try{
					Filter.filter(message, true); //throw error to escape sending message
					if(  message.to() != null && Application.isJabbifyNode() ){
						Global.sendMessage(message);
					}
			  }catch(FilterException e){
				  //just don't do anything with it
			  }catch(Throwable thr){
					logger.error("Caught Error ", thr);
			  }
			  
		       //System.out.println("\n = {"+message.type()+":"+message.action());
		        //if(message.type.equals("admin")){
		        //	message.filter();
		        //}
		        //message.putInInboxes();
			}catch(RuntimeException e){
				logger.error("RuntimeException in MessageEventListener", e);
				throw e;
		    }catch(Exception e){
				logger.error("Exception in MessageEventListener", e);
		    }
	}

}
